package org.example.controller;

import org.example.data.Result;
import org.example.data.User;
import org.example.data.UserMessage;
import org.example.data.UserWithDetails;
import org.example.tool.MySQL;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class UserController {

    public Result<User> login(String username, String password) {
        // 假设登录逻辑需要查询数据库，这里演示调用 getUser 方法
        try {
            User user = getUser(username);
            if (user != null && user.getPassword().equals(password)) {
                return new Result<>(true, "登录成功", user);
            } else {
                return new Result<>(false, "用户名或密码错误", null);
            }
        } catch (SQLException e) {
            System.out.println("数据库查询出错：" + e.getMessage());
            return new Result<>(false, "数据库查询出错", null);
        }
    }
    public Result<UserMessage> getUserMessage(Integer id){
        try {
            UserMessage user = selectUserMessage(id);
            if (user != null) {
                return new Result<>(true, "查询成功", user);
            } else {
                return new Result<>(false, "用户信息错误", null);
            }
        } catch (SQLException e) {
            System.out.println("数据库查询出错：" + e.getMessage());
            return new Result<>(false, "数据库查询出错", null);
        }
    }

    public Result<Integer> sign(String username, String password) {
        try {
            User user = getUser(username);
            if (user != null && user.getPassword().equals(password)) {
                return new Result<>(false, "账户已存在", 0);
            } else {
                Integer n = insertUser(username,password);
                if (n == 1){
                    user = getUser(username);
                    insertUserMessage(user.getId());
                    return new Result<>(true,"注册成功",1);
                }
                return new Result<>(false,"注册成功",n);
            }
        } catch (SQLException e) {
            System.out.println("数据库查询出错：" + e.getMessage());
            return new Result<>(false, "数据库查询出错", 1);
        }
    }

    public Result<Integer> update(Integer id, String password,String passwordTwo) {
        try {
            if (password.equals(getPassword(id))){
                Integer n = updatePassword(id, passwordTwo);
                if (n == 1){
                    return new Result<>(true,"修改成功",1);
                }
                return new Result<>(false,"修改失败",n);
            }else {
                return new Result<>(false,"原密码错误",0);
            }
        } catch (SQLException e) {
            System.out.println("密码修改过程中出现错误：" + e.getMessage());
            return new Result<>(false, "修改密码失败", null);
        }
    }

    private User getUser(String username) throws SQLException {
        MySQL mySQL = new MySQL();
        String sql = "select * from user where username = ?";
        PreparedStatement statement = mySQL.getStatement(sql);
        statement.setString(1, username); // 设置查询参数
        ResultSet resultSet = statement.executeQuery(); // 执行查询

        User user = null;
        if (resultSet.next()) {
            int id = resultSet.getInt("id");
            String password = resultSet.getString("password");
            String userType = resultSet.getString("usertype");
            user = new User(id, username, password,userType);
        }
        resultSet.close();
        statement.close();
        mySQL.close();
        return user;
    }

    private Integer insertUser(String username, String password) throws SQLException {
        MySQL mySQL = new MySQL();
        String sql = "insert into user (username, password,usertype) values (?, ?, ?)";
        PreparedStatement statement = mySQL.getStatement(sql);
        statement.setString(1, username);
        statement.setString(2, password);
        statement.setString(3,"普通用户");
        int n = statement.executeUpdate(); // 执行插入操作
        statement.close();
        mySQL.close();

        return n;
    }
    private Integer insertUserMessage(Integer userId) throws SQLException {
        MySQL mySQL = new MySQL();
        String sql = "insert into usermessage (userid,name,phonenumber,sex,age) values (?, 'admin', 11111111111, '未知', '18')";
        PreparedStatement statement = mySQL.getStatement(sql);
        statement.setInt(1, userId);
        int n = statement.executeUpdate(); // 执行插入操作
        statement.close();
        mySQL.close();

        return n;
    }
    private String getPassword(Integer id) throws SQLException {
        MySQL mySQL = new MySQL();
        String sql = "select password from user where id = ?";
        PreparedStatement statement = mySQL.getStatement(sql);
        statement.setInt(1, id); // 设置查询参数
        ResultSet resultSet = statement.executeQuery(); // 执行查询

        String password = null;
        if (resultSet.next()) {
            password = resultSet.getString("password");
        }
        resultSet.close();
        statement.close();
        mySQL.close();
        return password;
    }

    private Integer updatePassword(Integer id, String password) throws SQLException {
        MySQL mySQL = new MySQL();
        String sql = "update user set password = ? where id = ?";
        PreparedStatement statement = mySQL.getStatement(sql);
        statement.setString(1, password);
        statement.setInt(2, id);
        int n = statement.executeUpdate(); // 执行更新操作
        statement.close();
        mySQL.close();
        return n;
    }
    private UserMessage selectUserMessage(Integer id) throws SQLException {
        MySQL mySQL = new MySQL();
        String sql = "select * from usermessage where userid = ?";
        PreparedStatement statement = mySQL.getStatement(sql);
        statement.setInt(1, id); // 设置查询参数
        ResultSet resultSet = statement.executeQuery(); // 执行查询

        UserMessage user = null;
        if (resultSet.next()) {
            int id1 = resultSet.getInt("id");
            String name = resultSet.getString("name");
            String phoneNumber = resultSet.getString("phoneNumber");
            String sex = resultSet.getString("sex");
            int age = resultSet.getInt("age");
            user = new UserMessage(id1,id,name,phoneNumber,sex,age);
            System.out.println(user);

        }
        resultSet.close();
        statement.close();
        mySQL.close();
        return user;
    }
    /**
     * 查询用户列表及每个用户的详细信息
     * @return 结果列表，包含用户基本信息及每个用户对应的详细信息
     * @throws SQLException
     */
    public Result<List<UserWithDetails>> listUsers() throws SQLException {
        List<UserWithDetails> userListWithDetails = new ArrayList<>();
        MySQL mySQL = new MySQL();

        // 首先查询所有用户基本信息
        String sqlUsers = "SELECT * FROM user";
        PreparedStatement statementUsers = mySQL.getStatement(sqlUsers);
        ResultSet resultSetUsers = statementUsers.executeQuery();

        while (resultSetUsers.next()) {
            User user = new User();
            user.setId(resultSetUsers.getInt("id"));
            user.setUsername(resultSetUsers.getString("username"));
            user.setUsertype(resultSetUsers.getString("usertype"));
            // 根据当前用户ID查询详细信息
            UserMessage userMessage = selectUserMessage(user.getId());
            // 将基本信息和详细信息组合成一个新的对象
            UserWithDetails userDetails = new UserWithDetails(user, userMessage);

            userListWithDetails.add(userDetails);
        }

        resultSetUsers.close();
        statementUsers.close();
        mySQL.close();

        if (!userListWithDetails.isEmpty()) {
            return new Result<>(true, "查询用户列表及详细信息成功", userListWithDetails);
        } else {
            return new Result<>(false, "没有找到用户信息", null);
        }
    }
    public Result<Integer> updateUserRole(Integer userId, String newUserType) throws SQLException {
        MySQL mySQL = new MySQL();
        String sql = "UPDATE user SET usertype = ? WHERE id = ?";
        PreparedStatement statement = mySQL.getStatement(sql);
        statement.setString(1, newUserType);
        statement.setInt(2, userId);

        int rowsAffected = statement.executeUpdate();
        statement.close();
        mySQL.close();

        if (rowsAffected > 0) {
            return new Result<>(true, "用户类型更新成功", rowsAffected);
        } else {
            return new Result<>(false, "用户不存在或更新失败", rowsAffected);
        }
    }

}